//
//  XQNetworkManager.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/1/27.
//

import Alamofire

let KDefaultUrl = "KXQTrackingIDFAInfo"

enum ResultError: Error {
    case failure(String)
}

class XQNetworkManager {

    static let shared = XQNetworkManager();
    
    var url : String = "http://8.212.163.251:8721/status"
    
    var globalDic : [String : Any] = [:]
    
    private init() {
        setupGlobDic()
    }
    
    private func setupGlobDic() {
        let sessionId = XQCache.getSessionId()
        
        globalDic["non"] = XQDeviceManager.appVersion()
        globalDic["shootings"] = XQDeviceManager.deviceModel()
        globalDic["officer"] = XQDeviceManager.idfv()
        globalDic["artitioning"] = XQDeviceManager.idfa()
        globalDic["we"] = XQDeviceManager.systemVersion()
        
        if (!sessionId.isEmpty) {
            globalDic["myriad"] = sessionId;
        }
    }
    
    public func setCountry(country : Int?) {
        guard let c = country else {return}
        globalDic["simple"] = String(c)
    }
    
    public func setSessionId(sessionId : String?) {
        guard let s = sessionId else {return}
        XQCache.saveSessionId(sessionId: s)
        globalDic["myriad"] = String(s)
    }
    
    public func getAbsolutePath(path: String) -> String {
        let fullURL = "\(url)\(path)"
        var paramValue = ""
        
        if !globalDic.isEmpty {
            var params : [String] = []
            for (key, value) in globalDic {
                if let valueString = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                    let param = "\(key)=\(valueString)"
                    params.append(param)
                }
            }
            paramValue = params.joined(separator: "&")
        }
        return "\(fullURL)?\(paramValue)"
    }
    
    public func getWebUrlAbsolutePath(path: String) -> String {
        var paramValue = ""
        
        if !globalDic.isEmpty {
            var params: [String] = []
            for (key, value) in globalDic {
                if let valueString = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                    let param = "\(key)=\(valueString)"
                    params.append(param)
                }
            }
            paramValue = params.joined(separator: "&")
        }
        if path.contains("?") {
            return "\(path)&\(paramValue)"
        } else {
            return "\(path)?\(paramValue)"
        }
    }
}

extension XQNetworkManager {
    func getRequest(url: String, completion: @escaping (XQNetBaseModel?,String) -> Void) {
        let absoluteUrl = getAbsolutePath(path: url)
        Alamofire.request(absoluteUrl).responseJSON { response in
            switch response.result {
            case .success(let value):
                // 这里使用 value，它是 Any 类型
                if let json = value as? [String: Any] {
                    if let model = XQNetBaseModel.deserialize(from: json) {
                        completion(model,"")
                    }
                }
            case .failure(let error):
                completion(nil,"\(error)")
            }
        }
    }
}

extension XQNetworkManager {
    func postRequest(url: String, parameters: [String: Any], completion: @escaping (XQNetBaseModel?,String) -> Void) {
        let absoluteUrl = getAbsolutePath(path: url)
        Alamofire.request(absoluteUrl, method: .post, parameters: parameters).responseJSON { response in
            switch response.result {
            case .success(let value):
                // 这里使用 value，它是 Any 类型
                if let json = value as? [String: Any] {
                    if let model = XQNetBaseModel.deserialize(from: json) {
                        completion(model,"")
                    }
                }
            case .failure(let error):
                completion(nil,"\(error)")
            }
        }
    }
}

extension XQNetworkManager {
    func uploadImage(url : String,parameters: [String: Any],imageData:Data, completion: @escaping (XQNetBaseModel?,String) -> Void) {
        let absoluteUrl = getAbsolutePath(path: url)
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                
                for (key, value) in parameters {
                    if let data = "\(value)".data(using: .utf8) {
                        multipartFormData.append(data, withName: key)
                    }
                }
                
                let fileName = "\(Date().timeIntervalSince1970).png"
                multipartFormData.append(imageData, withName:"privilegeFaces", fileName:fileName, mimeType: "image/png")
            },
            to: absoluteUrl,
            headers: nil, // 可以在这里添加请求头
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        switch response.result {
                        case .success(let value):
                            if let json = value as? [String: Any] {
                                if let model = XQNetBaseModel.deserialize(from: json) {
                                    completion(model,"")
                                }
                            }
                        case .failure(let error):
                            completion(nil,"\(error)")
                        }
                    }
                case .failure(let error):
                    completion(nil,"\(error)")
                }
            }
        )
    }
}
